<template>
  <div class="the-header">
    <div class="header-logo" @click="goHome">
      <svg class="icon">
        <use xlink:href="#icon-erji"></use>
      </svg>
      <span>music</span>
    </div>
    <ul class="navbar">
<!--  左侧菜单栏    -->
      <li :class="{active: item.name === activeName}" v-for="item in navMsg" :key="item.path" @click="goPage(item.path,item.name)">
        {{item.name}}
      </li>
      <li>
        <div class="header-search">
          <input type="text" placeholder="搜索乐谱"  @keyup.enter="goSearch()" v-model="keywords"/>
            <div class="search-btn" @click="goSearch()">
              <svg class="icon">
                <use xlink:href="#icon-sousuo"></use>
              </svg>
            </div>
        </div>
      </li>

<!--  右侧菜单栏    -->
      <li v-show="!loginStatus" :class="{active: item.name === activeName}" v-for="item in loginMsg" :key="item.path" @click="goPage(item.path,item.name)">
        {{item.name}}
      </li>
    </ul>
    <div class="header-right" v-show="loginStatus">
      <div id="user" class="user-avator">
       <img :src="sConsumer.avatar"/>
      </div>
      <el-dropdown class="user-name" trigger="click" >
                <span class="el-dropdown-link">
                    {{sConsumer.username}}
                    <i class="el-icon-caret-bottom"></i>
                </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="avatar">上传头像</el-dropdown-item>
          <el-dropdown-item @click.native="openUpdateDialog">修改密码</el-dropdown-item>
          <el-dropdown-item >
            <span @click="logout">退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <!-- 修改头像弹窗 -->
    <el-dialog title="上传头像" :visible.sync="dialogFormVisible" width="30%">
      <el-form ref="addForm" >
        <!--头像-->
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="true"
          :multiple="true"
          :auto-upload="false"
          :on-change="handleChange"
          :file-list="fileList"
          list-type="picture-card"
        >
          <img v-if="form.avatar" :src="form.avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForms">确 定</el-button>
      </div>
    </el-dialog>
    <!--修改密码弹窗 -->
    <el-dialog title="修改密码" :visible.sync="updatePwdDialogFormVisible" width="20%" >
      <el-form ref="addForm" size="mini">
        <el-form-item label="旧密码" >
          <el-input v-model="formPwd.oldPassword" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码" >
          <el-input v-model="formPwd.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" >
          <el-input v-model="formPwd.confirmPassword" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" size="mini">
        <el-button @click="updatePwdDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitFormPwd">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters} from 'vuex';
import {navMsg,loginMsg} from "@/assets/data/header";
import {updatePwd, uploadAvatar} from "../api";

export default {
  name: "the-header",
  data(){
    return{
      navMsg:[],//左侧导航栏
      keywords:'',//搜索关键字
      loginMsg:[],//右侧导航栏
      updatePwdDialogFormVisible:false,
      dialogFormVisible:false,//默认不展示
      fileList:[],
      addForm: {
        file: '',
        id:''
      },
      form:{},
      formPwd: {
        oldPassword: '',
        password: '',
        confirmPassword:'',
      },
      sConsumer: JSON.parse(localStorage.getItem('sConsumer')) || {},//从浏览器里取数据，
    }
  },
  computed:{
    ...mapGetters([
      'activeName',
      'loginStatus',
    ])
  },
  created() {
    this.navMsg = navMsg;
    this.loginMsg = loginMsg;
    this.watchSetSConsumer()
  },

  methods:{
    // 登录后修改sConsumer
    watchSetSConsumer(){
      this.$bus.$on('setSConsumer',(sConsumerInfo)=>{
        Object.assign(this.sConsumer,sConsumerInfo)
      })
    },
    logout(){
      this.$store.commit('setLogOut');
      this.$router.push('/login-in');
      this.sConsumer = {}
    },
    //提示信息
    notify(title,type){
      this.$notify({
        title:title,
        type:type
      })
    },
    //上传头像
    avatar(){
      this.dialogFormVisible = true//打开弹窗
    },
    // 阻止upload的自己上传，进行再操作
    handleChange(file) {
      this.addForm.file = file.raw;
      this.addForm.id = this.sConsumer.id;
      this.fileList=[file];
    },
    submitForms() { // 新增表单提交
      this.dialogFormVisible = false;
      const formData = new FormData();
      const {id,file} = this.addForm;
      if(file==='') return alert('请选择头像')
      formData.append('file',file);
      formData.append('id',id);
      uploadAvatar(formData).then(newAvatarUrl=>{
        this.sConsumer.avatar = newAvatarUrl;
        localStorage.setItem('sConsumer',JSON.stringify(this.sConsumer));
        this.fileList.splice(0,1)
      })
    },
    goHome(){
      this.$router.push({path:'/'})
    },
    //导航栏页面跳转
    goPage(path,name){
      if (this.sConsumer.id==null && path==='/my-staff'){
        this.notify('请先登录','warning')
      }else {
        this.$store.commit('setActiveName',name);
        this.$router.push({path:path});
      }
    },
    //搜索
    goSearch(){
      this.$router.push({path:"/search",query:{keywords:this.keywords}})
    },
    //修改密码
    openUpdateDialog(){
      Object.assign(this.formPwd,
        {
          oldPassword: '',
          password: '',
          confirmPassword:'',
        });
      this.updatePwdDialogFormVisible = true;
    },
    //修改密码
    submitFormPwd(){
      const {username,id } = this.sConsumer;
      const {confirmPassword,password,oldPassword} = this.formPwd;
      if (password !==confirmPassword){
        this.$message.error("两次输入的密码不一致")
        return false
      }
      updatePwd({
        id,
        username,
        password,
        oldPassword
      }).then(res=>{
        const {message} = res;
        if (res.code === 200) {
          this.updatePwdDialogFormVisible  = false;
          return this.$message({
            type: "success",
            message
          })
        } else {
          return this.$message({
            type: "error",
            message
          });
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.user-avator{
  margin-left: 20px;
}

.user-avator img{
  display: block;
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.user-name{
  margin-left: 10px;
}

.el-dropdown-link{
  color: black;
  cursor: pointer;
}
@import "../assets/css/the-header.scss";
</style>
